import { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Avatar, Button, message, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { useModel } from 'umi';

import request from '@/utils/request';

import styles from './BaseView.less';

const UploadAvatar = ({ avatarUrl }) => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState.currentUser;
  const [imgSrc, setImgSrc] = useState(avatarUrl);

  return (
    <>
      <div className={styles.avatar_title}>头像</div>
      <div className={styles.avatar}>
        <Avatar src={<img src={imgSrc} alt="avatar" />} size={140} />
      </div>
      <ImgCrop showGrid cropShape="round">
        <Upload
          showUploadList={false}
          beforeUpload={(file) => {
            const formData = new FormData();
            formData.append('file', file);
            request(`/api/upload_avatar/${currentUser.id}`, {
              method: 'POST',
              data: formData,
              requestType: 'form',
            }).then((res) => {
              if (res.success) {
                message.success('头像上传成功！！！');
                setImgSrc(res.data);
              }
            });
          }}
        >
          <div className={styles.button_view}>
            <Button>
              <UploadOutlined />
              更换头像
            </Button>
          </div>
        </Upload>
      </ImgCrop>
    </>
  );
};

export default UploadAvatar;
